package com.request.service.impl.shop.happy;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.RechargeTypeEnum;
import com.request.common.utils.HttpUtils;
import com.request.entity.PhoneOrderWaitCheck;
import com.request.service.QueryOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description:
 * Create DateTime: 2020/5/22 10:54
 *
 * 

 */
@Slf4j
@Service
public class HappyQueryOrderProcessor implements QueryOrderProcessor {

    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Override
    public void sendRequest(PhoneOrderWaitCheck orderWaitCheck) {
        handlerOrderExecutor.execute(() -> executeWaitOrderQuery(orderWaitCheck));
    }

    /**
     * 执行待查询订单查询
     */
    private void executeWaitOrderQuery(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        Map<String, Object> params = new HashMap<>();
        String result = null;
        try {
            String querySite = phoneOrderWaitCheck.getQuerySite();
            String platformOrderNo = phoneOrderWaitCheck.getPlatformOrderNo();
            String appId = phoneOrderWaitCheck.getAppId();

            String sign = SecureUtil.md5(appId + platformOrderNo + phoneOrderWaitCheck.getAppKey());

            params.put("mchid", appId);
            params.put("orderid", platformOrderNo);
            params.put("sign", sign);
            log.info("【Happy】【查单】请求参数:{}", params);
            result = sendRequestForWaitOrder(querySite, params);
            log.info("【Happy】【查单】结果:{}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);

            phoneOrderWaitCheck.setShopOrderNo(jsonObject.getString("order_id"));
            //1 未支付 2 支付中 3 已支付 4 支付失败
            String status = jsonObject.getString("status");

            if ("3".equals(status)) {
                phoneOrderWaitCheck.setStatus(1);
                saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
            } else if ("4".equals(status)) {
                phoneOrderWaitCheck.setStatus(0);
                saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
            } else {
                saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
            }

        } catch (Exception e) {
            saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
            log.error("【Happy】【超时检查】请求商户出现异常，待检查订单信息为：{}, 参数为：{}, 响应结果为:{}, 详情为：{}",
                    phoneOrderWaitCheck, params.toString(), result, e);
        }
    }

    /**
     * 放入成功队列
     */
    private void saveWaitOrderQueryForSuccess(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_SUCCESS, JSON.toJSONString(phoneOrderWaitCheck));
    }

    private String sendRequestForWaitOrder(String url, Map<String, Object> params) {
        return HttpUtils.doPost(url, params);
    }

    /**
     * 放入处理中队列
     */
    private void saveWaitOrderQueryForProcessing(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        if (!RechargeTypeEnum.SLOW.getCode().equals(phoneOrderWaitCheck.getRechargeType())) {
            redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_PROCESSING, JSON.toJSONString(phoneOrderWaitCheck));
        }
    }
}
